package com.wwwarehouse.common.activity.base;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.multidex.MultiDex;
import android.text.TextUtils;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.iflytek.cloud.SpeechUtility;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.TbsListener;
import com.tendcloud.tenddata.TCAgent;
import com.wwwarehouse.common.BuildConfig;
import com.wwwarehouse.common.R;
import com.wwwarehouse.common.bean.address.AddressBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.db.DbUtils;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.FileUtils;
import com.wwwarehouse.common.tools.ImageloaderUtils;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.common.tools.SharedPreferencesHelper;
import com.wwwarehouse.common.tools.ThreadUtils;
import com.yolanda.nohttp.NoHttp;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import cn.sharesdk.framework.ShareSDK;
import de.greenrobot.event.EventBus;

import static com.wwwarehouse.common.constant.Constant.sp_Address_Version;
import static com.wwwarehouse.common.constant.Constant.sp_Token;

/**
 * Created by jack.dong on 2017/5/31.
 */

public class BaseApplication extends Application implements Application.ActivityLifecycleCallbacks {

    static BaseApplication instance = null;
    List<AddressBean> list;
    List<String> mNations;
    private String APP_ID = null;
    public static SharedPreferencesHelper sp = null;
    DisplayImageOptions mOptions;
    DisplayImageOptions mRoundOptions;
    ImageLoader mImageLoader = null;
    ImageLoader mRoundImageLoader = null;
    ImageLoadingListener mAnimateFirstListener = null;
    public static final int ADDRESS_VERSION_REQUEST_CODE = 1;
    public static final int ADDRESS_LIST_REQUEST_CODE = 2;
    public static final int READ_ADDRESS_IN_JSON = 3;
    public static final int REQUEST_LOGIN_WITH_TOKEN = 4;

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            switch (what) {
                case READ_ADDRESS_IN_JSON:
                    String json = (String) msg.obj;
                    //得到地址的实体类对象
                    try {
                        JSONObject object = new JSONObject(json);
                        JSONArray array = object.getJSONArray("data");
                        list = new ArrayList<>();
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject jsonObject = (JSONObject) array.get(i);
                            AddressBean bean = new AddressBean();
                            bean.setPARENT_AREA_ID(jsonObject.optString("parentAreaId"));
                            bean.setAREA_LEVEL(jsonObject.optString("areaType"));
                            bean.setAREA_NAME(jsonObject.optString("areaName"));
                            bean.setAREA_ID(jsonObject.optString("areaId"));
                            list.add(bean);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    ThreadUtils.newThread(new Runnable() {
                        @Override
                        public void run() {
                            DbUtils.deleteAllCity(BaseApplication.this);
                            DbUtils.saveCitys(list, BaseApplication.this);

                        }
                    });

                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(base);
    }

    @Override
    public void onCreate() {
        super.onCreate();

        instance = this;

        if(sp == null){
            sp = new SharedPreferencesHelper(this);
        }
        // 初始化科大讯飞语音播报和语音识别
//       SpeechUtility.createUtility(this, "appid=58d4dacc");

        SpeechUtility.createUtility(this, "appid=5330f55a");

        // 初始化NoHttp
        NoHttp.initialize(this,new NoHttp.Config());

        //ShareSDK初始化
        ShareSDK.initSDK(this);

        // 初始化图片缓存
        initImageLoader();

        // 初始化x5内核
        initX5WebView();

        //极光推送
        initJpush();

        checkAddressVersion();

        //初始化56个民族数据
        initNations();

        //ARouter
        initArouter();

        //刷新token
        refreshToken();

        logConfig();

        /**
         * 灵动分析初始化  appid 与  渠道id  以此来区分渠道的不同
         */
        // 如果已经在AndroidManifest.xml配置了App ID和渠道ID，调用TCAgent.init(this)即可；或与AndroidManifest.xml中的对应参数保持一致。
        TCAgent.init(this);
        TCAgent.setReportUncaughtExceptions(true);

        registerActivityLifecycleCallbacks(this);

        // 初始化到不同app的变量
        if (BuildConfig.AppName.equals(Constant.WANGCANG3)) {
            APP_ID = "wxb716f229c6313a0e";
        }
        else if (BuildConfig.AppName.equals(Constant.VORES)) {
            APP_ID = "wx782b4e3ff11422fd";
        }
    }

    public void logConfig(){
        //默认环境是真是环境
        if(sp.getValue(Constant.sp_EnvDefault, Constant.ENV_DEFAULT).equals(Constant.ENV_RELEASE)){
            //本应用日志
            LogUtils.setDebug(false);
            //灵动 日志记录
            TCAgent.LOG_ON = false;
        }else{//其他的环境打开日志
            //本应用日志
            LogUtils.setDebug(true);
            //ARouter
            ARouter.openDebug();
            ARouter.openLog();
            //灵动 日志记录
            TCAgent.LOG_ON = true;
        }
    }

    private void refreshToken() {
        if (!TextUtils.isEmpty(sp.getValue(sp_Token))) {
            Map map = new HashMap();

            map.put("deviceType", "a");

            NoHttpUtils.httpPost(Constant.URL_LOGIN_WITH_TOKEN, map, mOnResponseListener, REQUEST_LOGIN_WITH_TOKEN);
        }
    }

    // 初始化Arouter
    private void initArouter() {
        ARouter.openDebug();
        ARouter.openLog();
        ARouter.init(this);
    }

    // 初始化极光推送
    private void initJpush() {
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
        JPushInterface.setLatestNotificationNumber(this, 3);
    }

    // 初始化x5内核
    private void initX5WebView() {
        /**
         * qq内核的使用
         * 搜集本地tbs内核信息并上报服务器，服务器返回结果决定使用哪个内核。
         */
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {
            @Override
            public void onViewInitFinished(boolean arg0) {
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                LogUtils.showInfoLog("onViewInitFinished is " + arg0);
            }

            @Override
            public void onCoreInitFinished() {
            }
        };
        QbSdk.setTbsListener(new TbsListener() {
            @Override
            public void onDownloadFinish(int i) {
            }

            @Override
            public void onInstallFinish(int i) {
            }

            @Override
            public void onDownloadProgress(int i) {
            }
        });

        //x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(), cb);
    }

    private void initNations() {
        mNations = new ArrayList<>();
        String[] nations = getResources().getStringArray(R.array.nations);
        for (String str : nations) {
            mNations.add(str);
        }
        if (mNations != null && DbUtils.getNations(BaseApplication.this).size() == 0) {
            ThreadUtils.newThread(new Runnable() {
                @Override
                public void run() {
                    DbUtils.saveNations(mNations, BaseApplication.this);
                }
            });
        }

    }

    private void getAddressJson() {
        //线程池读取本地json文件
        ThreadUtils.newThread(new Runnable() {
            @Override
            public void run() {
                String jsonStr = FileUtils.getJson(getApplicationContext(), "address.json");
                Message msg = new Message();
                msg.what = READ_ADDRESS_IN_JSON;
                msg.obj = jsonStr;
                mHandler.sendMessage(msg);
            }
        });
    }

    private void getAddressRequest() {
        NoHttpUtils.httpPost(Constant.GET_ROUTER_AREA, new HashMap(), mOnResponseListener, ADDRESS_LIST_REQUEST_CODE);
    }

    private void checkAddressVersion() {
        NoHttpUtils.httpPost(Constant.GET_ADDRESS_VERSION, new HashMap(), mOnResponseListener, ADDRESS_VERSION_REQUEST_CODE);
    }

    public static BaseApplication getApplicationInstance() {
        return instance;
    }

    public void setStatusDark(Activity activity, boolean isDark) {
        setMeizuStatusBarDarkIcon(activity, isDark);
        setMiuiStatusBarDarkMode(activity, isDark);
    }

    private boolean setMiuiStatusBarDarkMode(Activity activity, boolean darkmode) {
        try {
            Class<? extends Window> clazz = activity.getWindow().getClass();
            int darkModeFlag = 0;
            Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
            Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            darkModeFlag = field.getInt(layoutParams);
            Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
            extraFlagField.invoke(activity.getWindow(), darkmode ? darkModeFlag : 0, darkModeFlag);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private boolean setMeizuStatusBarDarkIcon(Activity activity, boolean dark) {
        boolean result = false;
        if (activity != null) {
            try {
                WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                        .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class
                        .getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                activity.getWindow().setAttributes(lp);
                result = true;
            } catch (Exception e) {
            }
        }
        return result;
    }

    // 初始化ImageLoader
    public void initImageLoader() {
        mImageLoader = ImageloaderUtils.getImageLoader();

        mRoundImageLoader = ImageloaderUtils.getImageLoader();

        mRoundOptions = ImageloaderUtils.initImageLoaderOption(new RoundedBitmapDisplayer(8));

        mOptions = ImageloaderUtils.initImageLoaderOption();

        mAnimateFirstListener = new ImageloaderUtils.AnimateFirstDisplayListener();
    }


    // 显示图片
    public void displayImg(String url, ImageView imgV) {
        try {
            mImageLoader.displayImage(url, imgV, mOptions, mAnimateFirstListener);
        } catch (Exception e) {

        }
    }

    // 显示圆角图片
    public void displayRoundImg(String url, ImageView imgV) {
        try {
            mRoundImageLoader.displayImage(url, imgV, mRoundOptions, mAnimateFirstListener);
        } catch (Exception e) {

        }
    }

    // 显示圆角图片
    public void displayRoundImgPixel(String url, ImageView imgV, int roundPixel) {
        try {
            mRoundOptions = new DisplayImageOptions.Builder().displayer(new RoundedBitmapDisplayer(roundPixel)) // 设置成圆角图片
                    .cacheOnDisk(true) // 设置下载的图片是否缓存在SD卡中
                    .cacheInMemory(true).imageScaleType(ImageScaleType.EXACTLY).build();
            mRoundImageLoader.displayImage(url, imgV, mRoundOptions, mAnimateFirstListener);
        } catch (Exception e) {

        }
    }

    //显示圆形图片
    public void displayRoundImage(String url , ImageView imageView){
        try {
            ImageloaderUtils.displayCircleImage(url,imageView);
        } catch (Exception e) {

        }
    }

    public Bitmap loadImage(String url) {
        return mImageLoader.loadImageSync(url, mOptions);
    }

    // 清除内存缓存
    public void clearMomeryCache(String imgUrl) {
        try {
            mImageLoader.getMemoryCache().remove(imgUrl);
            mImageLoader.getMemoryCache().get(imgUrl).recycle();
        } catch (Exception e) {

        }
    }

    // 清除单张图片的内存以及sdcard存储
    public void clearSingleImageCache(String url) {
        clearMomeryCache(url);
        mImageLoader.getDiskCache().remove(url);
    }

    // 获取状态栏高度
    public int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    // 获取版本号
    public String getVersionCode() {
        PackageManager packageManager = getPackageManager();
        PackageInfo packageInfo;
        String versionCode = "";
        try {
            packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
            versionCode = packageInfo.versionCode + "";
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    // 获取版本名
    public String getVersionName() {
        PackageManager packageManager = getPackageManager();
        PackageInfo packageInfo;
        String versionName = "";
        try {
            packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
            versionName = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName.replace("v", "").replace("V", "");
    }

    public boolean isShowFingerPop() {
        return isShowFingerPop;
    }

    public void setShowFingerPop(boolean showFingerPop) {
        isShowFingerPop = showFingerPop;
    }

    private boolean isShowFingerPop;
    NoHttpUtils.OnResponseListener mOnResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(final CommonClass commonClass, int what) {
            switch (what) {
                case ADDRESS_VERSION_REQUEST_CODE:
                    if ("0".equals(commonClass.getCode()) && commonClass.getData() != null) {
                        if (!TextUtils.isEmpty(commonClass.getData().toString())) {
                            if (!sp.getValue(sp_Address_Version, "1.0").equals(commonClass.getData().toString())) {
                                getAddressRequest();
                            } else {
                                //因为本地asset里保存的数据是1.0版本的,所以只有在版本是1.0的时候读取本地，否则什么都不做
                                if (sp.getValue(sp_Address_Version, "1.0").equals("1.0")) {
                                    getAddressJson();
                                }
                            }
                            sp.putValue(sp_Address_Version, commonClass.getData().toString());

                        }
                    } else {
                        getAddressJson();
                    }
                    break;
                case ADDRESS_LIST_REQUEST_CODE:
                    if ("0".equals(commonClass.getCode()) && commonClass.getData() != null) {
                        ThreadUtils.newThread(new Runnable() {
                            @Override
                            public void run() {
                                //得到地址的实体类对象
                                try {
                                    String json = commonClass.getData().toString();
                                    JSONArray array = new JSONArray(json);
                                    list = new ArrayList<>();
                                    for (int i = 0; i < array.length(); i++) {
                                        JSONObject jsonObject = (JSONObject) array.get(i);
                                        AddressBean bean = new AddressBean();
                                        bean.setPARENT_AREA_ID(jsonObject.optString("parentAreaId"));
                                        bean.setAREA_LEVEL(jsonObject.optString("areaType"));
                                        bean.setAREA_NAME(jsonObject.optString("areaName"));
                                        bean.setAREA_ID(jsonObject.optString("areaId"));
                                        list.add(bean);
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                DbUtils.deleteAllCity(BaseApplication.this);
                                DbUtils.saveCitys(list, BaseApplication.this);
                            }
                        });

                    }
                    break;
                case REQUEST_LOGIN_WITH_TOKEN:
                    LogUtils.showLog("REQUEST_LOGIN_WITH_TOKEN"+commonClass.getCode());
                    if ("0".equals(commonClass.getCode())) {
                        isShowFingerPop = true;
                    } else {

                    }
                    break;
            }
        }

        @Override
        public void onFailed(String result, int what) {

        }

        @Override
        public void onFinish(int what) {
            switch (what) {
                case ADDRESS_VERSION_REQUEST_CODE:
                    getAddressJson();
                    break;
            }

        }
    };

    private int activityNum = 0;
    private boolean isBackToFrount;
    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

    }

    @Override
    public void onActivityStarted(Activity activity) {
        activityNum++;
        LogUtils.showLog("onActivityStarted" + activityNum + "isBackToFrount==="+isBackToFrount+"Constant.isTakePhotoFinished=="+Constant.isTakePhotoFinished);
        if (isBackToFrount && Constant.isTakePhotoFinished) {
            isBackToFrount = false;
            EventBus.getDefault().post("FINGER");
        }
    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {
        activityNum--;
        LogUtils.showLog("onActivityStarted" + activityNum + "isBackToFrount==="+isBackToFrount+"Constant.isTakePhotoFinished=="+Constant.isTakePhotoFinished);
        if (activityNum == 0) {
            isBackToFrount = true;
        }
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

    }

    public String getAPP_ID(){
        return APP_ID;
    }

}
